/**
 * 易驰护运 - MapComponentWeb
 * http://menger.me
 * 地图
 * @huanhaun
 */

'use strict';

import React from 'react';
import {
    Text,
    View,
    StatusBar,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
} from 'react-native';
import {
    IconFont,
} from '../../components'
import { Geolocation } from 'react-native-baidu-map'
import Webview from 'react-native-webview'


const injectedJavascript = `(function() {
    window.postMessage = function(data) {
      window.ReactNativeWebView.postMessage(data);
    };
  })()`;

export default class MapComponentWeb extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            // uri: 'http://suya.3todo.com/user/amap',
            uri: '',
            longitude: '',
            latitude: '',
        };
    }

    componentDidMount () {
        this.getCurrentPosition()
    }

    // 请求位置
    getCurrentPosition = () => {
        Geolocation.getCurrentPosition()
        .then(data => {
            console.log('地理位置', data)
            this.setState({
                longitude: data.longitude,
                latitude: data.latitude,
            }, () => this.requestData())
        })
        .catch(e => {console.log('error---->', e)})
    }

    requestData = async () => {
        let {default_address} = this.params;
        let {longitude, latitude} = this.state;
        let url = ServicesApi.INDEX_BAIDU_MAP;
        let data = {
            type: 1,
            longitude,  
            latitude,
            default_address: default_address,
            keyword: '',
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                uri: result.data.url,
            });
        }
    }

    onMessage = (event) => {
        let {markersType, getAddress} = this.params;
        console.log(event.nativeEvent.data);
        getAddress && getAddress(markersType ,event.nativeEvent.data)
        RouterHelper.goBack()
    }
    

    render() {
        let {uri} = this.state;
        return (
            <PageContainer style={styles.container}>
                <NavigationBar title={'地图'}/>
                <Webview
                    source={{uri}}
                    onLoadEnd={this.onLoadEnd}
                    startInLoadingState={false}
                    style={[styles.webContainer]}
                    injectedJavaScript={injectedJavascript} // 注入js代码
                    onMessage={(event) => this.onMessage(event)}
                />
            </PageContainer>
        )
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    webContainer: {
        height: '100%',
    },
})